package com.zhkj.txg.module.home.ui

import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.ShopAdapter
import com.zhkj.txg.module.home.adapter.ShopHomeCateAdapter
import com.zhkj.txg.module.home.entity.ShopEntity
import com.zhkj.txg.module.home.vm.ShopViewModel
import com.zhkj.txg.utils.GridItemDecoration
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_shop.*

class ShopActivity : ViewModelActivity<ShopViewModel>() {

    companion object {
        private val SHOP_ID = "shopId"
        private val TITLE = "title"

        fun open(context: Context, title: String, shopId: Int) {
            val intent = Intent(context, ShopActivity::class.java)
                .putExtra(SHOP_ID, shopId).putExtra(TITLE, title)
            context.startActivity(intent)
        }
    }

    override fun setViewModel(): ShopViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleShop
    override val layoutResId: Int = R.layout.activity_shop

    private val requestRefresh = 1000

    private lateinit var tvShopName: TextView
    private lateinit var tvShopGoodsCount: TextView
    private lateinit var tvShopFansCount: TextView
    private lateinit var tvShopCollect: TextView
    private lateinit var ivShopTop: ImageView
    private lateinit var rvShopCate: RecyclerView
    private val shopAdapter = ShopAdapter()
    private val shopCateAdapter = ShopHomeCateAdapter()

    override fun initUI() {
        with(rvShop) {
            layoutManager = GridLayoutManager(context, 2).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
            }
            addItemDecoration(
                GridItemDecoration(
                    ScreenUtil.dip(this@ShopActivity, 10),
                    ScreenUtil.dip(this@ShopActivity, 10)
                )
            )
            adapter = shopAdapter
        }
        with(shopAdapter) {
            headerWithEmptyEnable = true
            setHeaderView(createHeaderView())
            setEmptyView(R.layout.layout_empty_data)
            loadMoreModule?.setOnLoadMoreListener {
                viewModel.searchProduct(shopCateAdapter.shopId)
            }
        }
        // 全部商品点击事件
        tvShopAllGoods.setOnClickListener {
            ProductListActivity.shopOpen(
                this, "全部商品",
                intent.getIntExtra(SHOP_ID, 0), 0
            )
        }
        // 全部分类点击事件
        tvShopAllCate.setOnClickListener {
            viewModel.shopLiveData.value?.response?.data?.let {
                ShopCategoryActivity.open(this, it, requestRefresh)
            }
        }
        // 设置标题
        titleShop.setTitleTextContent(intent.getStringExtra(TITLE))
    }

    override fun initData() {
        shopCateAdapter.shopId = intent.getIntExtra(SHOP_ID, 0)
        viewModel.shopDetail(AccountManager.getToken(), intent.getIntExtra(SHOP_ID, 0))
        viewModel.searchProduct(shopCateAdapter.shopId, true)
    }

    override fun initViewModel() {
        viewModel.shopLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                // 数据填充
                titleShop.setTitleTextContent(it.shopName)
                tvShopName.text = it.shopName
                tvShopGoodsCount.text = String.format(getString(R.string.sale_count), it.goodsCount)
                tvShopFansCount.text = String.format(getString(R.string.fans_count), it.collectCount)
                tvShopCollect.isSelected = it.isCollect
                tvShopCollect.text =
                    getString(if (it.isCollect) R.string.followed else R.string.not_follow)
                ImageUtils.loadCircleImage(this@ShopActivity, ivShopTop, it.shopImg)
                shopCateAdapter.setNewData(it.cat)
            }
        })
        viewModel.followLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                tvShopCollect.isSelected = it.isFollow
                tvShopCollect.text =
                    getString(if (it.isFollow) R.string.followed else R.string.not_follow)
                tvShopFansCount.text = String.format(getString(R.string.fans_count), it.followCount)
                toast(getString(if (it.isFollow) R.string.followed else R.string.followed_cancel))
            }
        })
        viewModel.shopAllProductLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (it.hasMore) shopAdapter.loadMoreModule?.loadMoreComplete()
                    else shopAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) shopAdapter.addData(it.data)
                    else shopAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    shopAdapter.loadMoreModule?.loadMoreFail()
                }
            }

        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == requestRefresh)
            (data?.getSerializableExtra("data") as? ShopEntity)?.let { shop ->
                tvShopCollect.isSelected = shop.isCollect
                tvShopCollect.text =
                    getString(if (shop.isCollect) R.string.followed else R.string.not_follow)
                tvShopFansCount.text = String.format(getString(R.string.fans_count), shop.collectCount)
                // 将数据放入ViewModel
                viewModel.shopLiveData.value?.response?.data?.let {
                    it.isCollect = shop.isCollect
                    it.collectCount = shop.collectCount
                }
            }
    }

    private fun createHeaderView(): View {
        return layoutInflater.inflate(R.layout.item_shop_top, null).apply {
            tvShopName = findViewById(R.id.tvShopName)
            tvShopGoodsCount = findViewById(R.id.tvShopGoodsCount)
            tvShopFansCount = findViewById(R.id.tvShopFansCount)
            tvShopCollect = findViewById(R.id.tvShopCollect)
            ivShopTop = findViewById(R.id.ivShopTop)
            rvShopCate = findViewById(R.id.rvShopCate)
            // 跳转搜索页面
            findViewById<View>(R.id.tvShopTopSearch).setOnClickListener {
                SearchActivity.shopOpen(this@ShopActivity, intent.getIntExtra(SHOP_ID, 0).toLong())
            }
            tvShopCollect.setOnClickListener {
                viewModel.followShop(
                    AccountManager.getToken(),
                    intent.getIntExtra(SHOP_ID, 0),
                    tvShopCollect.isSelected
                )
            }
            with(rvShopCate) {
                layoutManager = LinearLayoutManager(this@ShopActivity, LinearLayoutManager.HORIZONTAL, false)
                adapter = shopCateAdapter
            }
        }
    }

}